package com.bilibili.lzx.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.bilibili.lzx.dao.UserMomentDao;
import com.bilibili.lzx.dao.domain.UserMoment;
import com.bilibili.lzx.dao.domain.constant.UserMomentsConstant;
import com.bilibili.lzx.dao.domain.exception.ConditionException;
import com.bilibili.lzx.service.util.RocketMQUtil;
import com.mysql.cj.util.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author lzx
 * @date 2024/9/2 20:07
 */

@Service
public class UserMomentService {

    @Resource
    private UserMomentDao userMomentDao;

    @Resource  //根据名称装配不能配合@Qualify使用，找不到根据类型      @Autowire根据类型装配
    private DefaultMQProducer momentProducer;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    public void addUserMoments(UserMoment userMoment) throws Exception {
        if(StringUtils.isNullOrEmpty(userMoment.getType())){
            throw new ConditionException("动态类型不能为空");
        }
        Date now = new Date();
        userMoment.setCreateTime(now);
        userMoment.setUpdateTime(now);
        userMomentDao.addUserMoments(userMoment);
        Message message = new Message(UserMomentsConstant.MOMENT_TOPIC, JSONObject.toJSONString(userMoment).getBytes(StandardCharsets.UTF_8));
        RocketMQUtil.syncSendMsg(momentProducer,message);
    }

    public List<UserMoment> getUserSubscribeMoment(Long currentUserId) {
        String value = redisTemplate.opsForValue().get("user_subscribe_moment_" + currentUserId);
        if(!StringUtils.isNullOrEmpty(value)){
            return JSONArray.parseArray(value, UserMoment.class);
        }
        return null;
    }
}
